package com.ptbuy.tranrecord;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ptbuy.MainActivity;
import com.ptbuy.R;
import com.ptbuy.callback.ExportMsgCall;
import com.ptbuy.db.dao.ClientDao;
import com.ptbuy.db.dao.ExportDao;
import com.ptbuy.db.dao.ProductDao;
import com.ptbuy.db.pojo.ClientPojo;
import com.ptbuy.db.pojo.ExportPojo;
import com.ptbuy.db.pojo.ProductPojo;
import com.ptbuy.signature.SingDialogAcvity;
import com.ptbuy.tranrecord.adapter.ExportViewAdapter;
import com.ptbuy.tranrecord.adapter.RecyclerViewAdapter;
import com.ptbuy.tranrecord.product.TranProductActivity;
import com.ptbuy.upload.Upload;
import com.ptbuy.utils.Constants;
import com.ptbuy.utils.ExportUtils;
import com.ptbuy.utils.MineType;
import com.ptbuy.utils.ToastUtil;
import com.ptbuy.utils.Utils;
import com.scwang.smart.refresh.footer.BallPulseFooter;
import com.scwang.smart.refresh.header.BezierRadarHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


/**
 * 交易记录
 */
public class TranRecordActivity extends AppCompatActivity {


    private ClientDao clientDao;
    private ProductDao productDao;
    private LinearLayout screenContent;
    private EditText choseCoumName, choseCoumPhone, choseAgentName;
    //总件数、总价、选中总价、选中总件数
    private TextView numProduct, numPrice, numCoum;

    //列表相关
    private SmartRefreshLayout smartRefreshLayout;
    private RecyclerView recyclerView;
    private int limit = 10;
    private int offset = 0;
    private String sqlParam = "";
    private List<ClientPojo> clientPojos;
    private LinearLayout historicalEmpty;
    private RecyclerViewAdapter adapter;

    private Upload upload;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tran_record);
        clientDao = new ClientDao();
        productDao = new ProductDao();
        upload = new Upload();
        //声明绑定控件
        smartRefreshLayout = findViewById(R.id.smart_refresh_layout);
        recyclerView = findViewById(R.id.recycler_view);
        //导出
        findViewById(R.id.recordExport).setOnClickListener(v -> {
            if (!Utils.hasAllFilesAccess()) {
                AlertDialog.Builder builder = new AlertDialog.Builder(TranRecordActivity.this);
                builder.setTitle("提示");
                builder.setMessage("导出操作需要打开文件所有权限，是否授权？");
                builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                        Uri uri = Uri.fromParts("package", Constants.CurrentContext.getPackageName(), null);
                        intent.setData(uri);
                        startActivity(intent);
                    }
                });
                builder.setNeutralButton("否", null);
                builder.show(); //调用show()方法来展示对话框
            } else {
                recordExport();
            }
        });
        findViewById(R.id.recordExportHor).setOnClickListener(v -> {
            recordExportHor();
        });

        numCoum = findViewById(R.id.numCoum);
        initData();//初始化列表

        init();//初始化

        initSum();

        setRefresh();//设置刷新逻辑
    }

    private void initData() {
        clientPojos = clientDao.queryRecodInfo(offset, limit, sqlParam);

        historicalEmpty = findViewById(R.id.historicalEmpty);
        if (clientPojos.size() > 0) {
            historicalEmpty.setVisibility(View.GONE);
        } else {
            historicalEmpty.setVisibility(View.VISIBLE);
        }
        //创建一个适配器对象，传一个集合进去给适配器
        adapter = new RecyclerViewAdapter(clientPojos, this);
        //设置垂直还是水平，三元表达式
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(RecyclerView.VERTICAL);

        adapter.setProjectInterface(new OptInterface());

        //设置方向
        manager.setReverseLayout(false);

        //把设置好的方向和排版给RecyclerView
        recyclerView.setLayoutManager(manager);

        //设置适配器器
        recyclerView.setAdapter(adapter);
    }

    private class OptInterface implements RecyclerViewAdapter.ClientInterface {

        @Override
        public void optProject(int type, ClientPojo dataBean, boolean isChecked) {
            /**
             * type 2、删除,删除的时候需要连下面的商品一起删除；3、查看照片视频
             */
            if (type == 2) {

                //删除
                AlertDialog.Builder builder = new AlertDialog.Builder(TranRecordActivity.this);
                builder.setTitle("提示");
                builder.setMessage("删除客户信息会将客户的商品一起删除，\n您确定删除吗？");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        int remove = clientDao.delInfo(String.valueOf(dataBean.getId()));
                        String msg = "删除失败";
                        if (remove != -1) {
                            msg = "删除成功";
                        }
                        Toast.makeText(TranRecordActivity.this, msg, Toast.LENGTH_LONG).show();
                        clientPojos.remove(dataBean);
                        adapter.notifyDataSetChanged();

                        /**
                         * 删除商品表
                         */
                        productDao.delInfoByPid(dataBean.getId());
                        initSum();//从新计算总件数和总价

                        upload.removeClientInfo(dataBean.getId());

                    }
                });
                builder.setNeutralButton("取消", null);
                builder.show(); //调用show()方法来展示对话框
            } else if (type == 3) {
                Intent intent = new Intent(TranRecordActivity.this, TranProductActivity.class);
                intent.putExtra("pid", dataBean.getId());
                startActivity(intent);
                finish();
            } else if (type == 4) {
                //修改
                View view = LayoutInflater.from(TranRecordActivity.this).inflate(R.layout.tran_modify, null);
                EditText tranCoumName = view.findViewById(R.id.tranCoumName);
                tranCoumName.setText(dataBean.getName());
                EditText tranCoumPhone = view.findViewById(R.id.tranCoumPhone);
                tranCoumPhone.setText(dataBean.getPhone());
                EditText tranAgentName = view.findViewById(R.id.tranAgentName);
                tranAgentName.setText(dataBean.getAgentName());
                AlertDialog.Builder builder123 = new AlertDialog.Builder(TranRecordActivity.this);
                builder123.setView(view);
                builder123.setTitle("信息修改");
                builder123.setCancelable(false);
                builder123.setPositiveButton("确定", null);
                builder123.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                AlertDialog alertDialog = builder123.create();
                alertDialog.show();
                alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        alertDialog.dismiss();
                        String tranCoumNameText = tranCoumName.getText().toString();//客户名称
                        String tranCoumPhoneText = tranCoumPhone.getText().toString();//客户电话
                        String tranAgentNameText = tranAgentName.getText().toString();//经纪人

                        Integer integer = clientDao.updateClientInfo(dataBean.getId(), tranCoumNameText, tranAgentNameText, tranCoumPhoneText);
                        if (integer > 0) {
                            ToastUtil.show(TranRecordActivity.this, "修改成功");

                            int i = clientPojos.indexOf(dataBean);
                            clientPojos.remove(dataBean);
                            dataBean.setName(tranCoumNameText);
                            dataBean.setPhone(tranCoumPhoneText);
                            dataBean.setAgentName(tranAgentNameText);

                            clientPojos.add(i, dataBean);
                            adapter.notifyDataSetChanged();

                            //上传后台
                            ClientPojo clientPojo = clientDao.queryClientInfo(dataBean.getId());
                            upload.modifyClientInfo(clientPojo);

                        } else {
                            ToastUtil.show(TranRecordActivity.this, "修改失败");
                        }
                    }
                });
            } else if (type == 5) {
                //查看签字确认单
                if (exportDao == null) {
                    exportDao = new ExportDao();
                }
                ExportPojo exportPojo = exportDao.queryExportPojoByClientid(dataBean.getId());
                if (exportPojo == null) {
                    ToastUtil.show(TranRecordActivity.this, "文件丢失或还未导出签字确认单");
                    return;
                }
                File file = new File(exportPojo.getExportFilePath());
                if (file.exists()) {
                    MineType.openFile(TranRecordActivity.this, file);
                } else {
                    ToastUtil.show(TranRecordActivity.this, "文件丢失或还未导出签字确认单");
                }
            } else if (type == 6) {


                if (!Utils.hasAllFilesAccess()) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(TranRecordActivity.this);
                    builder.setTitle("提示");
                    builder.setMessage("导出签字确认单需要打开文件所有权限才能导出成功，是否授权？");
                    builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                            Uri uri = Uri.fromParts("package", Constants.CurrentContext.getPackageName(), null);
                            intent.setData(uri);
                            startActivity(intent);
                        }
                    });
                    builder.setNeutralButton("否", null);
                    builder.show(); //调用show()方法来展示对话框
                } else {
                    if (exportDao == null) {
                        exportDao = new ExportDao();
                    }
                    clientPojoID = dataBean.getId();
                    //导出签字确认单
                    AlertDialog.Builder builder = new AlertDialog.Builder(TranRecordActivity.this);
                    builder.setTitle("提示");
                    builder.setMessage("客户重新签名确认");
                    builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                            Intent intent = new Intent(TranRecordActivity.this, SingDialogAcvity.class);
                            startActivityForResult(intent, 888);
                        }
                    });
                    builder.setNeutralButton("否", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            List<ProductPojo> pojoList = productDao.queryInfo(0, 0, " and pid ='" + clientPojoID + "'");
                            exportPdf(pojoList, null);
                        }
                    });
                    builder.show(); //调用show()方法来展示对话框
                }
            }
        }
    }

    String clientPojoID = null;


    private void exportPdf(List<ProductPojo> productPojos, String signatureFilePath) {

        Long totalPriceInfo = 0L;
        String totalPrice = "0";
        for (ProductPojo pd : productPojos) {
            totalPriceInfo += Long.parseLong(pd.getProductPrice().replace(",", ""));
        }
        if (totalPriceInfo > 0) {
            totalPrice = Utils.getNumlStr(totalPriceInfo.toString());
        }

        ExportUtils.exportPDF(productPojos, signatureFilePath, this, String.valueOf(productPojos.size()), totalPrice, new ExportMsgCall() {
            @Override
            public void exportFile(String backFilePath) {
                if (backFilePath == null) {
                    Message obtainMessage = mHandler.obtainMessage();
                    obtainMessage.what = 3;
                    mHandler.sendMessage(obtainMessage);
                } else {
                    filePath = backFilePath;
                    Message obtainMessage = mHandler.obtainMessage();
                    obtainMessage.what = 2;
                    mHandler.sendMessage(obtainMessage);
                }
            }
        });
    }


    private void initSum() {
        //总价
        try {
            Long totalPriceInfo = 0L;
            List<String> list = clientDao.queryTotalPriceInfo();
            for (String sttr : list) {
                totalPriceInfo += Long.parseLong(sttr.replace(",", ""));
            }

            if (totalPriceInfo > 0) {
                mytotalPrice = Utils.getNumlStr(totalPriceInfo.toString());
            } else {
                mytotalPrice = "0";
            }

            numPrice.setText(mytotalPrice);

            //总件数
            Integer totalProductInfo = clientDao.queryTotalProductInfo();
            numProduct.setText(String.valueOf(totalProductInfo));
            mytotalProduct = String.valueOf(totalProductInfo);
            numCoum.setText(String.valueOf(clientDao.queryCount()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //初始化
    private void init() {

        choseCoumName = findViewById(R.id.choseCoumName);//客户姓名
        choseCoumPhone = findViewById(R.id.choseCoumPhone);//客户电话
        choseAgentName = findViewById(R.id.choseAgentName);//收  购  人
        numProduct = findViewById(R.id.numProduct);
        numPrice = findViewById(R.id.numPrice);

        //返回
        findViewById(R.id.back).setOnClickListener(v -> {
            back();
        });
        //筛选框
        screenContent = findViewById(R.id.screenContent);
        //点击筛选框
        findViewById(R.id.screen).setOnClickListener(v -> {
            screenContent.setVisibility(View.VISIBLE);
        });
        //关闭筛选框
        findViewById(R.id.closeScreen).setOnClickListener(v -> {
            screenContent.setVisibility(View.GONE);
            sqlParam = "";
            initSum();
            clientPojos.clear();
            List<ClientPojo> myClientPojos = clientDao.queryRecodInfo(0, limit, sqlParam);
            clientPojos.addAll(myClientPojos);
            adapter.notifyDataSetChanged();
        });
        //点击筛选查询
        findViewById(R.id.searchScreen).setOnClickListener(v -> {
            String choseCoumNameText = choseCoumName.getText().toString();
            String choseCoumPhoneText = choseCoumPhone.getText().toString();
            String choseAgentNameText = choseAgentName.getText().toString();
            sqlParam = " 1=1 ";
            if (!"".equalsIgnoreCase(choseCoumNameText)) {
                sqlParam += " and name like '%" + choseCoumNameText + "%' ";
            }
            if (!"".equalsIgnoreCase(choseCoumPhoneText)) {
                sqlParam += " and phone like '%" + choseCoumPhoneText + "%' ";
            }
            if (!"".equalsIgnoreCase(choseAgentNameText)) {
                sqlParam += " and agent_name like '%" + choseAgentNameText + "%' ";
            }
            clientPojos.clear();
            List<ClientPojo> myClientPojos = clientDao.queryRecodInfo(0, 0, sqlParam);
            clientPojos.addAll(myClientPojos);
            adapter.notifyDataSetChanged();
            mathPrice();
        });


    }

    /**
     * 计算总件数和总价
     */
    String mytotalProduct;
    String mytotalPrice;

    private void mathPrice() {
        Long sum = 0L;
        Integer totalProduct = 0;
        for (ClientPojo pp : clientPojos) {
            sum += Long.parseLong(pp.getTotalPrice().replace(",", ""));
            totalProduct += pp.getTotalProduct();
        }
        String dealPrice = Utils.getNumlStr(sum.toString());
        mytotalPrice = dealPrice;
        numPrice.setText(dealPrice);
        //总件数
        mytotalProduct = String.valueOf(totalProduct);
        numProduct.setText(mytotalProduct);
    }

    /*
     * 设置刷新的方法
     * */
    private void setRefresh() {

        //设置头部刷新的样式
        smartRefreshLayout.setRefreshHeader(new BezierRadarHeader(this));
        //设置页脚刷新的样式
        smartRefreshLayout.setRefreshFooter(new BallPulseFooter(this));
        //设置头部刷新时间监听
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                smartRefreshLayout.finishRefresh(500/*,false*/);//传入false表示刷新失败
//                //添加一条新数据，再最开头的位置
//                offset = 0;
//                items = productDao.queryInfo(offset, limit, sqlParam);
//                adapter.notifyDataSetChanged();
            }
        });
        /**
         * 上拉加载更多-
         */

        smartRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                smartRefreshLayout.finishLoadMore(999);///延迟999毫秒后结束刷新
                offset = offset + limit;
                if (clientPojos.size() == 0 || clientPojos.size() < 10) {
                    smartRefreshLayout.finishLoadMore(true);
                    offset = offset - limit;
                    Toast.makeText(TranRecordActivity.this, "到底了", Toast.LENGTH_SHORT).show();
                    return;
                }

                List<ClientPojo> dataBean = clientDao.queryRecodInfo(offset, limit, sqlParam);

                if (dataBean.size() == 0) {
                    smartRefreshLayout.finishLoadMore(true);
                    offset = offset - limit;
                    Toast.makeText(TranRecordActivity.this, "到底了", Toast.LENGTH_SHORT).show();
                } else {

                    smartRefreshLayout.finishLoadMore(true);
                    //添加一条新数据，再最后的位置
                    for (int i = 0; i < dataBean.size(); i++) {
                        clientPojos.add(clientPojos.size(), dataBean.get(i));
                    }
                    adapter.notifyDataSetChanged();

                    Toast.makeText(TranRecordActivity.this, "刷新成功", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    private void back() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            back();
        }
        return false;
    }


    /**
     * ---------------------------------------------------导出
     */
    //导出记录
    private void recordExportHor() {
        exportRecords();
    }

    int exportType = 0;

    //导出
    private void recordExport() {
        // 定义一个字符串数组作为单选项
        String[] items = {"导出签字确认单", "导出Excel"};

        // 创建AlertDialog
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("选择导出类型");
        builder.setCancelable(false);
        builder.setSingleChoiceItems(items, exportType, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 这里的which参数表示选中的单选按钮的索引
                // 可以在这里处理选中事件，例如更新UI或者存储选中的值
                exportType = which;
            }
        });
        builder.setNegativeButton("取消", null);
        builder.setPositiveButton("确定", null);

        // 创建并显示对话框
        AlertDialog dialog = builder.create();
        dialog.show();

        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 检查是否已经授予权限
                if (ContextCompat.checkSelfPermission(TranRecordActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    // 请求权限
                    ActivityCompat.requestPermissions(TranRecordActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                } else {
                    // 已经授予权限，执行导出Excel文件的操作
                    if (exportType != 2) {
                        dialog.dismiss();
                    }
                    exportFile();
                }
            }
        });
    }

    ExportDao exportDao;

    private void exportFile() {
        if (exportDao == null) {
            exportDao = new ExportDao();
        }
        List<ProductPojo> productPojos = new ArrayList<>();
        if (!"".equalsIgnoreCase(sqlParam)) {
            for (ClientPojo cp : clientPojos) {
                List<ProductPojo> pojoList = productDao.queryInfo(0, 0, " and pid='" + cp.getId() + "'");
                productPojos.addAll(pojoList);
            }

        } else {
            productPojos = productDao.queryInfo(0, 0, null);
        }
        int size = productPojos.size();
        if (size == 0) {
            ToastUtil.show(TranRecordActivity.this, "没有数据可以导出");
            return;
        }
        if (exportType == 0) {
            //导出PDF
            ExportUtils.exportPDF(productPojos, null, this, mytotalProduct, mytotalPrice, new ExportMsgCall() {
                @Override
                public void exportFile(String backFilePath) {
                    if (backFilePath == null) {
                        Message obtainMessage = mHandler.obtainMessage();
                        obtainMessage.what = 3;
                        mHandler.sendMessage(obtainMessage);
                    } else {
                        filePath = backFilePath;
                        Message obtainMessage = mHandler.obtainMessage();
                        obtainMessage.what = 2;
                        mHandler.sendMessage(obtainMessage);
                    }
                }
            });

//            exportPDF(productPojos);
        } else if (exportType == 1) {
            //导出Excel
            ExportUtils.exportExcel(productPojos, this, new ExportMsgCall() {
                @Override
                public void exportFile(String backFilePath) {
                    if (backFilePath == null) {
                        Message obtainMessage = mHandler.obtainMessage();
                        obtainMessage.what = 3;
                        mHandler.sendMessage(obtainMessage);
                    } else {
                        filePath = backFilePath;
                        Message obtainMessage = mHandler.obtainMessage();
                        obtainMessage.what = 2;
                        mHandler.sendMessage(obtainMessage);

                    }
                }
            });
//            exportExcel(productPojos);
        }
    }


    String filePath;


//    //导出Text
//    private void exportText(List<ProductPojo> recodInfos) {
//
//        ProgressDialog progressDialog = new ProgressDialog(this);
//        progressDialog.setTitle("提示");
//        progressDialog.setMessage("正在导出");
//        progressDialog.setCancelable(false);
//        progressDialog.show();
//        new Thread(() -> {
//            FileOutputStream fos = null;
//            OutputStreamWriter osw = null;
//            BufferedWriter writer = null;
//            try {
//                String currentTime = Utils.getCurrentTime(new Date());
//                filePath = Constants.getExportFilePath() + currentTime + ".txt";
//
//                File file = new File(filePath);
//                fos = new FileOutputStream(file);
//                osw = new OutputStreamWriter(fos);
//                writer = new BufferedWriter(osw);
//
//                for (ProductPojo recodInfo : recodInfos) {
//                    writer.newLine();
//                    String content = "id：" + recodInfo.getId() +
//                            ",名称：" + recodInfo.getProductName() +
//                            ",价格：" + recodInfo.getProductPrice() +
//                            ",计录时间：" + recodInfo.getTime() +
//                            ",客户名称：" + recodInfo.getClientPojo().getName() == null ? "" : recodInfo.getClientPojo().getName() +
//                            ",收购人：" + recodInfo.getClientPojo().getAgentName() == null ? "" : recodInfo.getClientPojo().getAgentName() +
//                            ",客户电话：" + recodInfo.getClientPojo().getPhone() == null ? "" : recodInfo.getClientPojo().getPhone() +
//                            ",照片路径：" + recodInfo.getMult() == null ? "" : recodInfo.getMult() + ";";
//                    writer.write(content);
//                }
//
//                exportDao.addInfo(filePath);
//
//                Message obtainMessage = mHandler.obtainMessage();
//                obtainMessage.what = 2;
//                mHandler.sendMessage(obtainMessage);
//            } catch (Exception e) {
//                e.printStackTrace();
//                Message obtainMessage = mHandler.obtainMessage();
//                obtainMessage.what = 3;
//                mHandler.sendMessage(obtainMessage);
//            } finally {
//                progressDialog.dismiss();
//                try {
//                    if (writer != null) {
//                        writer.close();
//                    }
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//                try {
//                    if (fos != null) {
//                        fos.close();
//                    }
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//                try {
//                    if (osw != null) {
//                        osw.close();
//                    }
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();
//
//    }

    List<ExportPojo> exportPojos;
    ExportViewAdapter exportViewAdapter;

    //导出计录
    private void exportRecords() {
        View view1 = LayoutInflater.from(this).inflate(R.layout.tran_historical_export, null);
        ListView listExport = view1.findViewById(R.id.listExport);

        if (exportDao == null) {
            exportDao = new ExportDao();
        }
        exportPojos = exportDao.queryExportPojo();

        exportViewAdapter = new ExportViewAdapter(this, exportPojos);
        exportViewAdapter.setProjectInterface(new MyExportViewInterface());
        listExport.setAdapter(exportViewAdapter);


        AlertDialog.Builder builder123 = new AlertDialog.Builder(this);
        builder123.setTitle("导出记录");
        builder123.setView(view1);
        builder123.setCancelable(true);
        builder123.setPositiveButton("关闭", null);
        AlertDialog alertDialog = builder123.create();
        alertDialog.show();
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay();  //为获取屏幕宽、高
        android.view.WindowManager.LayoutParams p = alertDialog.getWindow().getAttributes();  //获取对话框当前的参数值
        p.height = (int) (d.getHeight() * 0.8);   //高度设置为屏幕的0.3
        alertDialog.getWindow().setAttributes(p);     //设置生效
    }

    private class MyExportViewInterface implements ExportViewAdapter.ExportViewInterface {

        @Override
        public void opt(ExportPojo dataBean) {
            AlertDialog.Builder builder = new AlertDialog.Builder(TranRecordActivity.this);
            builder.setTitle("提示");
            builder.setMessage("您确定删除吗？");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    exportPojos.remove(dataBean);
                    exportDao.delInfo(dataBean.getId());
                    exportViewAdapter.notifyDataSetChanged();
                    Constants.deleteFile(dataBean.getExportFilePath());
                }
            });
            builder.setNeutralButton("取消", null);
            builder.show(); //调用show()方法来展示对话框

        }
    }

    private Handler mHandler = new Handler() {

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 2:
                    exportSuccess();
                    break;
                case 3:
                    ToastUtil.show(TranRecordActivity.this, "导出异常");
                    break;
            }
        }

        ;
    };

    private void exportSuccess() {
        AlertDialog.Builder builder = new AlertDialog.Builder(TranRecordActivity.this);
        builder.setTitle("导出成功");
        builder.setMessage("存放位置：" + filePath);
        builder.setPositiveButton("打开文件", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                File file = new File(filePath);
                if (file.exists()) {
                    MineType.openFile(TranRecordActivity.this, file);
                } else {
                    ToastUtil.show(TranRecordActivity.this, "文件丢失");
                }
            }
        });
        builder.setNeutralButton("关闭", null);
        builder.show(); //调用show()方法来展示对话框
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { //申请文件读写权限
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            exportFile();
        }
    }

    String singaturePath;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 888 && resultCode == RESULT_OK && data != null) {
            singaturePath = data.getExtras().getString("path");
            clientDao.updateSignatureFilePath(clientPojoID, singaturePath);

            List<ProductPojo> pojoList = productDao.queryInfo(0, 0, " and pid ='" + clientPojoID + "'");

            exportPdf(pojoList, singaturePath);
        }
    }
}